﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using XsqTech.SmartOA.Domain.Table;
using XsqTech.SmartOA.Dtos.DTO;
using XsqTech.SmartOA.EFCore.Respository;
using XsqTech.SmartOA.IRespository;
using XsqTech.SmartOA.IService;
using XsqTech.SmartOA.Service.DTO;

namespace XsqTech.SmartOA.Service
{
    public class DepartmentService:IDepartmentService
    {
        IDepartmentUserRespository _baseDepartmentUser;
        IUserRespository _userRespository;
        IDepartmentRespository _baseDepartment;
        readonly IMapper _mapper;
        readonly IUnitOfWork _unitOfWork;
        private readonly ILogger<FormService> _logger;

        public DepartmentService(IDepartmentUserRespository baseDepartmentUser, IUserRespository userRespository, IDepartmentRespository baseDepartment, IMapper mapper, IUnitOfWork unitOfWork, ILogger<FormService> logger)
        {
            _baseDepartmentUser = baseDepartmentUser;
            _userRespository = userRespository;
            _baseDepartment = baseDepartment;
            _mapper = mapper;
            _unitOfWork = unitOfWork;
            _logger = logger;
        }



        /// <summary>
        /// 部门树形的显示
        /// </summary>
        /// <returns></returns>
        public List<Department> GetDepartTree()
        {
            var slist = _baseDepartment.Query().Where(x => x.CascadeId == "0").ToList();
            ChildrenMshow(slist);
            return slist.Where(x => x.IsChecks == 0).ToList();
        }
        /// <summary>
        /// 调用的递归方法
        /// </summary>
        /// <param name="dd"></param>
        private void ChildrenMshow(List<Department> dd)
        {
            foreach (var item in dd)
            {
                item.Dlist = new List<Department>();
                item.Dlist = _baseDepartment.Query().Where(x => x.ParentId == item.DepId).ToList();
                ChildrenMshow(item.Dlist);
            }
        }
        /// <summary>
        /// 部门分页显示
        /// </summary>
        /// <param name="departmentPageDto"></param>
        /// <returns></returns>
        public PageList<DepartmentDto> DShow(DepartmentPageDto departmentPageDto)
        {
            var ls = from a in _baseDepartment.Query().Where(x => x.IsChecks == 0)
                     select
                     new DepartmentDto
                     {
                         Account = string.Join(',', (from B in _userRespository.Query()
                                                     join C in _baseDepartmentUser.Query() on B.Id equals C.UId
                                                     where C.DepId == a.DepId
                                                     select B.UserName)
                                                     .ToArray()),
                         DUId = a.DepId.ToString(),
                         Name = a.Name,
                         ParentId = a.ParentId.ToString(),
                         Status = a.Status,
                         IsChecks = a.IsChecks,
                         DepId = a.DepId.ToString(),
                         CascadeId = a.CascadeId,
                         PName = (from d in _baseDepartment.Query()
                                  where a.ParentId == d.DepId
                                  select d.Name).SingleOrDefault() ?? "根节点",
                     };
            if (!string.IsNullOrEmpty(departmentPageDto.did))
            {
                ls = ls.Where(x => x.CascadeId.Contains(departmentPageDto.did));
            }
            if (!string.IsNullOrEmpty(departmentPageDto.names))
            {
                ls = ls.Where(x => x.Name.Contains(departmentPageDto.names));
            }

            PageList<DepartmentDto> p = new()
            {
                TotalCount = ls.Count(),
                PList = ls.OrderBy(x => x.DepId)
                             .Skip((departmentPageDto.Pindex - 1) * departmentPageDto.Psize)
                             .Take(departmentPageDto.Psize)
                             .ToList(),
            };
            return p;
        }
        /// <summary>
        /// 返填数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Department GIt(Guid id)
        {
            return _baseDepartment.GetById(id);
        }
        /// <summary>
        /// 部门修改
        /// </summary>
        /// <param name="department"></param>
        /// <returns></returns>
        public MsgResponse<UptDepartmentsDto> Update(UptDepartmentsDto department)
        {
            var s = _mapper.Map<Department>(department);
            _baseDepartment.Update(s);
            int data = _unitOfWork.SaveChangs();
            if (data > 0)
            {
                MsgResponse<UptDepartmentsDto> responseModel = new()
                {
                    Code = 200,
                    Msg = "修改成功!",
                    Data = department,
                };
                return responseModel;
            }
            else
            {
                MsgResponse<UptDepartmentsDto> responseModel = new()
                {
                    Code = 401,
                    Msg = "修改失败!",
                };
                return responseModel;
            }
        }
        /// <summary>
        /// 部门的添加
        /// </summary>
        /// <param name="department"></param>
        /// <returns></returns>
        public MsgResponse<AddDepartmentsDto> Add(AddDepartmentsDto department)
        {
             Department departments = new Department()
            {
                Name = department.Name,
                ParentId = Guid.Parse(department.ParentId),
                Status = department.Status
            };
            if (department.ParentId == "00000000-0000-0000-0000-000000000000")
            {
                string d = (_baseDepartment.Query().Where(x => x.ParentId == departments.ParentId).Count() + 1).ToString();
                string dar = _baseDepartment.Query().Where(x => x.DepId == departments.ParentId).SingleOrDefault() + $"{d}.";
                departments.CascadeId = dar;
            }
            else
            {
                string d = (_baseDepartment.Query().Where(x => x.ParentId == null).Count() + 1).ToString();
                departments.CascadeId = $".0.{d}.";
            }
            //添加
            _baseDepartment.Add(departments);
            //实例化结果返回模型
            int res = _unitOfWork.SaveChangs();
            if (res > 0)
            {
                MsgResponse<AddDepartmentsDto> responseModel = new MsgResponse<AddDepartmentsDto>()
                {
                    Code = 200,
                    Msg = "添加成功!",
                    Data = department,
                };
                return responseModel;
            }
            else
            {
                MsgResponse<AddDepartmentsDto> responseModel = new MsgResponse<AddDepartmentsDto>()
                {
                    Code = 401,
                    Msg = "添加失败!",
                };
                return responseModel;
            }
        }
        /// <summary>
        /// 为部门添加用户
        /// </summary>
        /// <param name="addDepartmentsUsersDto"></param>
        /// <returns></returns>
        public int AddDepartmentsUser(AddDepartmentsUsersDto addDepartmentsUsersDto)
        {
            return _baseDepartment.AddDepartmentsUser(addDepartmentsUsersDto.DepId, addDepartmentsUsersDto.Id);
        }
        /// <summary>
        /// 部门添加用户
        /// </summary>
        /// <param name="addDepartmentsUsersDto"></param>
        /// <returns></returns>
        public ResponseModel AddDepartmentsUser1(AddDepartmentsUsersDto addDepartmentsUsersDto)
        {
            try
            {
                string[] id = addDepartmentsUsersDto.Id.Split(',');
                foreach (var item in id)
                {
                    DepartmentUser departmentUser = new DepartmentUser();
                    departmentUser.DepId = addDepartmentsUsersDto.DepId;
                    departmentUser.UId = Guid.Parse(item);
                    _baseDepartmentUser.Add(departmentUser);
                }
                int data = _unitOfWork.SaveChangs();
                if (data > 0)
                {
                    return new ResponseModel
                    {
                        Code = State.请求成功,
                        Message = "添加成功",
                        Count = data,
                    };
                }
                else
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "添加失败",
                        Count = data,
                    };
                }

            }
            catch (Exception ex)
            {
                //控制台输出
                Console.WriteLine(ex.Message);
                //写入日志
                _logger.LogError(ex.Message);
                throw;
            };
        }

        /// <summary>
        /// 部门的删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResponseModel Del(string id)
        {
            try
            {
                var list = _baseDepartment.Query().FirstOrDefault(x => x.DepId.ToString().Equals(id));
                _baseDepartment.Delete(list!.DepId);
                int data = _unitOfWork.SaveChangs();
                if (data > 0)
                {
                    return new ResponseModel
                    {
                        Code = State.请求成功,
                        Message = "删除成功",
                        Count = data,
                    };
                }
                else
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "删除失败",
                        Count = data,
                    };
                }
            }
            catch (Exception ex)
            {
                //控制台输出
                Console.WriteLine(ex.Message);
                throw;
            };
        }

        /// <summary>
        /// 部门删除（批删）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ResponseModel AllDepartmentDelete(List<DepartmentDto> dto)
        {
            try
            {
                foreach (var item in dto)
                {
                    var list = _baseDepartment.Query().FirstOrDefault(x => x.DepId.ToString() == item.DepId);
                    if (list != null)
                    {
                        _baseDepartment.Delete(list.DepId);
                    }
                    else
                    {
                        return new ResponseModel
                        {
                            Code = State.请求失败,
                            Message = "删除失败",
                        };
                    }
                }
                int data = _unitOfWork.SaveChangs();
                if (data > 0)
                {
                    return new ResponseModel
                    {
                        Code = State.请求成功,
                        Message = "删除成功",
                        Count = data,
                    };
                }
                else
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "删除失败",
                        Count = data,
                    };
                }
            }
            catch (Exception ex)
            {
                //控制台输出
                Console.WriteLine(ex.Message);
                //写入日志
                _logger.LogError(ex.Message);
                throw;
            };

        }
    }
}
